import { StyleSheet, Text } from 'react-native'
import React, { useState, useImperativeHandle, forwardRef } from 'react'
import { Actionsheet, Box } from 'native-base'
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
import { uploadURL } from '../../axios';
import RNFetchBlob from "rn-fetch-blob";

const MyActionsheet = ({ visible = false, onSuccess }, ref) => {
  const [isOpen, setIsOpen] = useState(visible)
  // 向父组件暴露方法
  useImperativeHandle(ref, () => ({
    open: onOpen,
    close: onClose
  }));

  const select = (type) => {
    if (type === 'camera') {
      launchCamera({
        mediaType: 'photo'
      }, success)
    } else if (type === 'image') {
      launchImageLibrary({
        mediaType: 'photo',
        // includeBase64: true,
        // includeExtra: true,
      }, success)
    }
    console.log('select')
    onClose()
  }
  const onOpen = () => {
    setIsOpen(true)
  }
  const onClose = () => {
    setIsOpen(false)
  }
  const success = async (e) => {
    const data = e.assets

    RNFetchBlob.fetch(
      "POST",
      uploadURL + '/upload',
      {
        "Content-Type": "multipart/form-data",
      },
      [
        // element with property `filename` will be transformed into `file` in form data
        {
          name: 'uploadImage',
          filename: data[0].fileName,
          type: data[0].type,
          data: RNFetchBlob.wrap(data[0].uri)
        }
      ]
    )
      .then((res) => {
        // ...
        console.log('上传成功', res)
        const imgData = JSON.parse(res.data)
        // setList([...list, ...data.map(item => ({ url: item.uri }))])
        onSuccess(imgData.data, data)
      })
      .catch((err) => {
        // ...
        console.log('上传失败', err)
      });
  }
  return (
    <Actionsheet isOpen={isOpen} onClose={onClose}>
      <Actionsheet.Content>
        <Box w="100%" h={60} px={4} justifyContent="center">
          <Text fontSize="16" color="gray.500" _dark={{
            color: 'gray.300'
          }} style={{ textAlign: 'center' }}>
            请选择
          </Text>
        </Box>
        <Actionsheet.Item onPress={() => select('camera')}>拍摄</Actionsheet.Item>
        <Actionsheet.Item onPress={() => select('image')}>从相册选择</Actionsheet.Item>
      </Actionsheet.Content>
    </Actionsheet>
  )
}

export default forwardRef(MyActionsheet)

const styles = StyleSheet.create({})